import { useState } from 'react';

import { useMutation } from '@apollo/client';
import { Button, Stack, TextField } from '@mui/material';

import { GET_TOKEN } from '../graphql';

interface LoginFormProps {
  fetchProducts: () => void;
}

export const LoginForm = ({ fetchProducts }: LoginFormProps) => {
  const [login, setLogin] = useState('');
  const [password, setPassword] = useState('');
  const [hasToken, setHasToken] = useState(false);

  const [getToken] = useMutation<{
    login: { accessToken: string };
  }>(GET_TOKEN);

  const handleGetToken = async () => {
    const { data, errors } = await getToken({
      variables: {
        login,
        password,
      },
    });

    if (errors) {
      console.log(errors);
      return;
    }

    if (!data) return;

    localStorage.setItem('token', data.login.accessToken);

    setHasToken(true);
  };

  return (
    <Stack direction='row' alignItems='center' spacing={1}>
      <TextField
        variant='outlined'
        size='small'
        label='Логин'
        value={login}
        onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
          setLogin(event.target.value);
        }}
      />
      <TextField
        variant='outlined'
        size='small'
        label='Пароль'
        type='password'
        value={password}
        onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
          setPassword(event.target.value);
        }}
      />
      <Button variant='outlined' onClick={handleGetToken}>
        Авторизоваться
      </Button>
      {hasToken && (
        <Button variant='outlined' onClick={() => fetchProducts()}>
          Получить данные
        </Button>
      )}
    </Stack>
  );
};
